<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\Notify as NotifyModel;
use app\payment\model\Download as DownloadModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 多次通知控制器
 */
class Notify extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'see', 'notify', 'export'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->add_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['edit'])) {
            if (!$this->edit_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = NotifyModel::where($map)->order('create_time desc')->paginate($list_rows);
        // 分页数据
        $page = $data_list->render();

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');

        $date = date('Y-m-d');
        $search = [
            ['daterange:6', 'create_time', '时间查询', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '通知状态', '', '', ['失败', '成功']],
            ['select:3', 'type', '支付类型', '', '', $all_payment_type],
            ['text:3', 'merchant_order_id', '商户订单号'],
            ['text:3', 'order_id', '平台订单号'],
            ['text:3', 'cash', '订单金额'],
            ['select:3', 'trade_type', '交易类型', '', '', $all_trade_type],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'merchant_id', '商户号'],
        ];

        $items = [
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_order_id', '商户订单号'],
            ['order_id', '平台订单号'],
            ['other_order_id', '第三方订单号'],
            ['trade_type', '交易类型', '', '', $all_trade_type],
            ['status', '通知状态', 'status', '', ['失败', '成功']],
            ['cash', '订单金额', 'callback', function ($cash) {
                return $cash / 100;
            }],
            ['type', '支付类型', '', '', $all_payment_type],
            ['count', '通知次数'],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['update_time', '更新时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['manual', '通知开关', 'status', '', ['开启:primary', '关闭:info']],
            ['right_button', '操作', 'btn']
        ];
        $hideCheckbox = false;
        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[7]);
            unset($search[8]);
            // 去掉显示列
            unset($items[0]);
            unset($items[3]);
            unset($items[11]);
            $hideCheckbox = true;
        }

        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $tips = "系统第一次通知您的url，返回的内容不是success，才会记录到这里，只表示订单通知失败，具体通知失败原因，点击查看！";

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox($hideCheckbox)
            ->setPageTitle('订单通知失败管理') // 设置页面标题
            ->setTableName('payment_order_notify') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->addColumns($items)
            ->addTopButtons('delete') // 批量添加顶部按钮
            ->addTopButton('export', $export) // 添加按钮 
            ->addRightButton('edit', ['href' => url('edit', ['order_id' => '__id__'])])
            ->addRightButtons('delete') // 批量添加右侧按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['order_id' => '__id__'])], true)
            ->addRightButton('notify', ['title' => '通知', 'class' => 'ajax-get confirm', 'icon' => 'fa fa-fw fa-forumbee', 'href' => url('notify', ['order_id' => '__id__'])])
            ->setSearchArea($search) // 设置搜索区域     
            ->setRowList($data_list) // 设置表格数据
            ->replaceRightButton(['manual' => 1], '', 'notify') // 替换右侧按钮
            ->replaceRightButton(['status' => 1], '', 'notify') // 替换右侧按钮
            ->setPages($page) // 设置分页数据
            ->setPageTips($tips)
            ->fetch(); // 渲染页面
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');

        $count = NotifyModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }
        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "订单通知失败导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败！");
        }

        $field = [
            'order_id',
            'merchant_id',
            'merchant_order_id',
            'other_order_id',
            'cash',
            'status',
            'type',
            'trade_type',
            'count',
            'create_time',
            'update_time',
        ];
        if ($this->no_auth) {
            unset($field[3]);
        }

        $cellName = [
            '平台订单号',
            '商户号',
            '商户订单号',
            '第三方订单号',
            '金额',
            '通知状态',
            '支付类型',
            '交易类型',
            '通知次数',
            '创建时间',
            '更新时间',
        ];
        if ($this->no_auth) {
            unset($cellName[3]);
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_order_notify')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_payment_type, $all_trade_type) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;
                    $single['status'] = $single['status'] == 1 ? '成功' : '失败';
                    $single['type'] = isset($all_payment_type[$single['type']]) ? $all_payment_type[$single['type']] : $single['type'];
                    $single['trade_type'] = isset($all_trade_type[$single['trade_type']]) ? $all_trade_type[$single['trade_type']] : $single['trade_type'];

                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 通知
     * @param string $order_id 主键
     * @return mixed
     */
    public function notify($order_id = null)
    {
        if ($order_id === null) {
            $this->error('缺少参数！');
        }
        // 获取数据
        $info = NotifyModel::where('order_id', $order_id)->field(true)->find();

        if (!$info) {
            $this->error('参数有误！');
        }
        $resdata = go_curl($info['url'], '', 'get', 12);
        if (stripos($resdata, 'success') !== false) {
            // 通知成功     
            NotifyModel::where('order_id', $order_id)
                ->inc('count')
                ->update(['update_time' => time(), 'status' => 1]);
            $this->error('通知成功！');
        } else {
            NotifyModel::where('order_id', $order_id)
                ->inc('count')
                ->update(['update_time' => time(), 'remark' => substr($resdata, 0, 60000)]);
        }

        $this->error("通知失败,返回内容是：{$resdata}");
    }

    /**
     * 编辑
     * @param null $order_id 
     * @return mixed
     */
    public function edit($order_id = null)
    {
        if ($order_id === null) {
            $this->error('缺少参数！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if (NotifyModel::where(['order_id' => $data['order_id']])->update($data)) {
                $temp = NotifyModel::where(['order_id' => $data['order_id']])->find();
                // 记录行为
                action_log('payment_notify_edit', 'notify', $temp['order_id'], UID, json_encode($temp));
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 获取数据
        $info = NotifyModel::where('order_id', $order_id)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        $info['type'] = isset($all_payment_type[$info['type']]) ? $all_payment_type[$info['type']] : $info['type'];
        $info['trade_type'] = isset($all_trade_type[$info['trade_type']]) ? $all_trade_type[$info['trade_type']] : $info['trade_type'];

        $info['cash'] /= 100;
        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'order_id', '平台订单号', '', '', true],
            ['static', 'merchant_order_id', '商户订单号'],
            ['static', 'other_order_id', '第三方订单号'],
            ['static', 'trade_type', '交易类型'],
            ['static', 'app_id', '应用ID'],
            ['static', 'cash', '金额（元）'],
            ['switch', 'status', '通知状态', '', '', '', 'disabled'],
            ['static', 'type', '支付类型'],
            ['radio', 'manual', '通知开关', '', ['开启', '关闭']],
            ['static', 'count', '通知次数'],
            ['textarea', 'url', '通知url', '', '', '', ''],
            ['textarea', 'remark', '返回内容[:无]', '', '', 'disabled', ''],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];
        $btn = [];
        if ($this->no_auth) {
            $btn = 'submit';
            unset($items[3]);
            unset($items[9]);
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn($btn)
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 查看
     * @param null $order_id 
     * @return mixed
     */
    public function see($order_id = null)
    {
        if ($order_id === null) {
            $this->error('缺少参数！');
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 获取数据
        $info = NotifyModel::where('order_id', $order_id)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if (isset($all_payment_type[$info['type']])) {
            $info['type'] = $all_payment_type[$info['type']];
        }
        if (isset($all_trade_type[$info['trade_type']])) {
            $info['trade_type'] = $all_trade_type[$info['trade_type']];
        }
        $info['cash'] /= 100;
        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'order_id', '平台订单号', '', '', true],
            ['static', 'merchant_order_id', '商户订单号'],
            ['static', 'other_order_id', '第三方订单号'],
            ['static', 'trade_type', '交易类型'],
            ['static', 'app_id', '应用ID'],
            ['static', 'cash', '金额（元）'],
            ['radio', 'status', '通知状态', '', ['失败', '成功']],
            ['static', 'type', '支付类型'],
            ['radio', 'manual', '通知开关', '', ['开启', '关闭']],
            ['static', 'count', '通知次数'],
            ['textarea', 'url', '通知url', '', '', '', ''],
            ['textarea', 'remark', '通知返回内容[:无]', '', '', 'disabled', ''],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];
        if ($this->no_auth) {
            unset($items[0]);
            unset($items[3]);
            unset($items[9]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = NotifyModel::where('order_id', 'in', $ids)->column('order_id');
        return parent::setStatus($type, ['payment_notify_' . $type, 'payment_notify', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = NotifyModel::where('order_id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['payment_notify_edit', 'payment_notify', $id, UID, $details]);
    }
}
